package com.itxiuyixiu.homework.config;

import com.itxiuyixiu.homework.entity.dao.AdminDao;
import com.itxiuyixiu.homework.entity.enums.RoleType;
import com.itxiuyixiu.homework.entity.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author 黄磊
 * @date 2020/3/9
 */
@Component
public class AdminRegister implements ApplicationRunner {
    private final AdminDao adminDao;
    private final PasswordEncoder passwordEncoder;

    public AdminRegister(AdminDao adminDao, PasswordEncoder passwordEncoder) {
        this.adminDao = adminDao;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (adminDao.existsByUsername("admin")) {
            return;
        }
        Admin admin = new Admin();
        admin.setUsername("admin");
        admin.setPassword(passwordEncoder.encode("123456"));
        admin.setAuthorities(RoleType.ADMIN);
        adminDao.save(admin);
    }
}
